<template>
  <Dialog
    :title="title"
    :visible="visible"
    :button-text="testBtn"
    :reveal="true"
    :width="widths"
    :loading="loading"
    class="dialogStyle two-columns"
    @close="handleClose"
    @confirm="submitForm"
  >
    <div v-if="flag">
      <el-form
        ref="from"
        v-loading="loading"
        :inline="true"
        :model="addCustomersData"
        :rules="rules"
        label-width="100px"
      >
        <div v-if="isModify" class="info-titles">基础信息</div>
        <el-row v-if="isModify">
          <el-col v-for="(item, index) in basicsInfo" :key="index" :span="item.name === '地区' || item.name === '备注' ? 24 : 12">
            <el-form-item
              v-if="item.systemStatus !== '不显示'"
              :label="item.name + '：'"
              :prop="item.type"
            >
              <el-input
                v-if="item.genre === 1"
                v-model="addCustomersData[item.type]"
              />
              <el-radio-group
                v-if="item.genre === 2"
                v-model="addCustomersData[item.type]"
              >
                <el-radio label="男" />
                <el-radio label="女" />
              </el-radio-group>
              <el-date-picker
                v-if="item.genre === 6"
                v-model="addCustomersData[item.type]"
                type="date"
                placeholder="选择生日"
              />
              <AreaSelector
                v-if="item.genre === 3"
                ref="areaSelector"
                style="width: 100%"
                :code.sync="addCustomersData.city"
                :default-value="addCustomersData.city"
              />
              <dictionary-selector
                v-if="item.genre === 4 && item.type !== 'attributionConsultantName'"
                class="el-select-y"
                :code="
                  item.name === '意向度'
                    ? 'swan_customer_yxd'
                    : item.name === '婚姻状况'
                      ? 'swan_cutomer_marriage'
                      : item.name === '血型'
                        ? 'swan_cutomer_blood'
                        : item.name === '体型'
                          ? 'swan_cutomer_size'
                          : ''
                "
                :value.sync="addCustomersData[item.type]"
              />
              <div v-if="item.genre === 5" class="editor">
                <editor-content class="editor__content" :editor="editor" />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="isModify">
          <div class="info-title">聊天工具资料</div>
        </el-row>
        <el-row v-if="isModify">
          <el-col
            v-for="(item, index) in chatToolInfo"
            :key="index"
            :span="12"
          >
            <el-form-item
              v-if="item.systemStatus !== '不显示'"
              :label="item.name + '：'"
              :prop="item.type"
            >
              <el-input
                v-if="item.genre === 1"
                v-model="addCustomersData[item.type]"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="isModify">
          <div class="info-title">顾客评级</div>
        </el-row>
        <el-row v-if="isModify">
          <el-col
            v-for="(item, index) in featuresInfo"
            :key="index"
            :span="item.name === '地区' || item.name === '备注' ? 24 : 12"
          >
            <el-form-item
              v-if="item.systemStatus !== '不显示' && item.type !== 'attributionConsultantName'"
              :label="item.name + '：'"
              :prop="item.type"
            >
              <dictionary-selector
                v-if="item.genre === 4 && item.type !== 'attributionConsultantName'"
                class="el-select-y"
                :code="
                  item.name === '意向度'
                    ? 'swan_customer_yxd'
                    : item.name === '婚姻状况'
                      ? 'swan_cutomer_marriage'
                      : item.name === '血型'
                        ? 'swan_cutomer_blood'
                        : item.name === '体型'
                          ? 'swan_cutomer_size'
                          : ''
                "
                :value.sync="addCustomersData[item.type]"
              />
              <el-rate v-if="item.genre === 7" v-model="addCustomersData[item.type]" style="margin-top: 6px;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="isModify && isInfo">
          <div class="info-title">归属信息</div>
        </el-row>
        <el-row v-if="isInfo">
          <el-col
            v-for="(item, index) in ascriptionInfo"
            :key="index"
            :span="12"
          >
            <el-form-item
              v-if="
                item.systemStatus !== '不显示' &&
                  item.type !== 'attributionConsultantName'
              "
              :label="item.name + '：'"
              :prop="item.type"
            >
              <el-input
                v-if="item.genre === 1"
                v-model="addCustomersData[item.type]"
              />
              <el-select
                v-if="item.genre === 4 && item.name === '来源类型'"
                v-model="addCustomersData[item.type]"
                placeholder="请选择"
                class="el-select-y"
                @change="channelChange"
              >
                <el-option
                  v-for="json in regions"
                  :key="json.id"
                  :label="json.name"
                  :value="json.id"
                />
              </el-select>
              <el-select
                v-if="item.genre === 4 && item.name === '来源名称'"
                v-model="addCustomersData[item.type]"
                placeholder="请选择"
                class="el-select-y"
                @change="channelNameChange"
              >
                <el-option
                  v-for="json in allChannel"
                  :key="json.id"
                  :label="json.name"
                  :value="json.id"
                />
              </el-select>
              <el-select
                v-if="item.genre === 4 && item.name === '开发人员'"
                v-model="addCustomersData[item.type]"
                class="el-select-y"
                placeholder="请选择"
                @change="developersChange"
              >
                <el-option
                  v-for="json in allDeveloper"
                  :key="json.id"
                  :label="json.usrName"
                  :value="json.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              v-if="
                item.systemStatus !== '不显示' &&
                  item.type === 'attributionConsultantName' &&
                  !isModify
              "
              :label="item.name + '：'"
              :prop="item.type"
            >
              <el-select
                v-model="addCustomersData.attributionConsultantId"
                placeholder="请选择"
                @change="attributionConsultantHandle"
              >
                <el-option
                  v-for="json in attributionConsultantList"
                  :key="json.id"
                  :label="json.usrName"
                  :value="json.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </Dialog>
</template>
<script>
import { Editor, EditorContent } from 'tiptap';
import { AreaSelector } from "@monkey.do/monkey";
import Dialog from "@/components/Dialog/index";
export default {
  components: {
    AreaSelector,
    Dialog,
    EditorContent,
  },
  props: {
    flag: {
      type: Boolean,
      default: true,
    },
    title: {
      type: String,
      default: "",
    },
    testBtn: {
      type: String,
      default: "保存",
    },
    visible: {
      type: Boolean,
      default: false,
    },
    currentRow: {
      type: Object,
      default: () => ({}),
    },
    isInfo: {
      type: Boolean,
      default: true,
    },
    isModify: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    // var validatorPhone = function(rule, value, callback) {
    //   if (!value) {
    //     callback(new Error('请输入手机号'));
    //   } else if (!/^1\d{10}$/.test(value)) {
    //     callback(new Error('手机号格式错误'));
    //   } else {
    //     callback();
    //   }
    // };
    return {
      attributionConsultantList: [],
      addCustomersData: {}, // 添加数据
      widths: 50,
      loading: false,
      rules: {},
      basicsInfo: [],
      ascriptionInfo: [],
      featuresInfo: [],
      allChannel: [],
      allDeveloper: [],
      editor: null,
      chatToolInfo: [],
      regions: [],
    };
  },
  computed: {
    name() {
      if (this.addCustomersData.city) {
        return this.addCustomersData.city;
      } else {
        return null;
      }
    },
  },
  watch: {
    name(val) {
      if (!val) return;
      if (this.isUpdate) {
        this.isUpdate = false;
        return;
      }
      let address = "";
      const cityCode = [];
      let list = [];
      if (this.$refs.areaSelector) {
        const cityList = this.$refs.areaSelector[0].provinces;
        if (val.provinceCode) {
          cityList.forEach((item) => {
            if (item.code === val.provinceCode) {
              address += item.name;
              list = item.childList;
              cityCode.push(item.code);
            }
          });
        }
      }
      if (val.cityCode) {
        list.forEach((item) => {
          if (item.code === val.cityCode) {
            address += item.name;
            list = item.childList;
            cityCode.push(item.code);
          }
        });
      }
      if (val.regionCode) {
        list.forEach((item) => {
          if (item.code === val.regionCode) {
            address += item.name;
            cityCode.push(item.code);
          }
        });
      }
      this.addCustomersData.address = address;
      this.addCustomersData.cityCode = cityCode.join(",");
    },
    currentRow: {
      handler(val) {
        if (this.isInfo && this.isModify) {
          this.getFindAll();
          this.getAllDeveloper();
        }
        if (!this.isInfo && this.isModify) {
          this.getFindAll(true, val);
        }
        if (this.isInfo && !this.isModify) {
          this.getFindAll(true);
          this.getAllChannel(
            val.developmentChannels ? val.developmentChannels : ""
          );
          this.getAllDeveloper();
          this.attributionConsultant();
        }
        this.addCustomersData = JSON.parse(JSON.stringify(val));
        if (this.addCustomersData.developmentChannelsId) {
          this.getAllChannel(this.addCustomersData.developmentChannelsId);
        } else {
          this.getAllChannel(undefined);
        }
      },
      deep: true,
      immediate: true,
    },
  },
  mounted() {
    this.getDicoptList();
  },
  methods: {
    // 获取来源类型
    getDicoptList() {
      this.$api["networkpower/sourceType/findAll"]().then((res) => {
        if (res.code !== 200) return this.$message.error(res.msg);
        this.regions = res.data;
      });
    },
    async getFindAll(flag, row) {
      this.basicsInfo = [];
      this.ascriptionInfo = [];
      this.featuresInfo = [];
      this.rules = {};
      if (!flag) this.addCustomersData = {};
      this.loading = true;
      const res = await this.$api["customer/setUp/findAll"]({});
      this.loading = false;
      if (res.code !== 200) return;
      let appendMessage;
      if (row && row.appendMessage) {
        appendMessage = JSON.parse(row.appendMessage);
      }
      res.data.tableConfigEntities.forEach((item) => {
        if (item.systemStatus === "不显示") {
          return;
        }
        if (item.genre === 5) {
          this.editor = new Editor({
            onUpdate: ({ state, getHTML, getJSON, transaction }) => {
              this.addCustomersData[item.type] = getHTML();
            },
            content: this.currentRow && this.currentRow.remark ? this.currentRow.remark : res.data.content,
          });
        }
        if (item.classify === "1") {
          this.basicsInfo.push(item);
        } else if (item.classify === "4") {
          this.ascriptionInfo.push(item);
        } else if (item.classify === "3") {
          this.chatToolInfo.push(item);
        } else {
          this.featuresInfo.push(item);
          if (appendMessage) {
            appendMessage.forEach((json) => {
              if (json.name === item.name) {
                this.addCustomersData[item.type] = json.value;
              }
            });
          }
        }
        if (item.systemStatus === "必填") {
          const message =
            item.genre === 1 || item.genre === 5 ? "输入" : "选择";
          const json = {
            required: true,
            message: "请" + message + item.name,
            trigger: item.genre === 1 || item.genre === 4 ? "blur" : "change",
          };
          this.$set(this.rules, item.type, [json]);
        }
      });
    },
    handleClose() {
      // this.$refs["from"].clearValidate();
      this.$emit("handleClose");
    },
    // 提交
    submitForm() {
      this.$refs.from.validate(async(valid) => {
        if (!valid) return;
        const list = [];
        this.loading = true;
        this.featuresInfo.forEach((item) => {
          if (item.property === "自定义" && this.addCustomersData[item.type]) {
            const json = {
              name: item.name,
              value: this.addCustomersData[item.type],
            };
            list.push(json);
          }
        });
        this.addCustomersData.appendMessage = JSON.stringify(list);
        this.addCustomersData.archivistName = this.archivistName;
        if (this.addCustomersData.birthday) {
          const date = new Date(this.addCustomersData.birthday);
          const year = date.getFullYear();
          const month = date.getMonth() + 1;
          const day = date.getDate();
          this.addCustomersData.birthday = year + "-" + month + "-" + day;
        }
        if (this.isModify && this.isInfo) {
          const res = await this.$api["customer/customers/add"]({
            ...this.addCustomersData,
          });
          this.loading = false;
          if (res.code !== 200) return this.$message.error(res.msg);
          this.$message.success("添加成功！");
          this.$emit("handleSuccess");
          // this.params.page = 1;
          // this.getCustomersList();
          // this.visible = false;
        } else {
          const res = await this.$api["customer/customers/modify"]({
            ...this.addCustomersData,
          });
          this.loading = false;
          if (res.code !== 200) return this.$message.error(res.msg);
          this.$message.success("修改成功！");
          this.$emit("handleSuccess");
          // this.params.page = 1;
          // this.getCustomersList();
          // this.visible = false;
        }
      });
    },
    attributionConsultantHandle(val) {
      this.attributionConsultantList.forEach((item) => {
        if (item.id === val) {
          this.addCustomersData.attributionConsultantName = item.usrName;
        }
      });
    },
    async attributionConsultant() {
      const res = await this.$api["data/hospitalStaff/getAllByJobName"]({
        hospitalJobName: "咨询师",
      });
      if (res.code !== 200) return;
      this.attributionConsultantList = res.data;
    },
    async getAllChannel(id) {
      const res = await this.$api["customer/customers/getAllSource"]({
        query: { typeId: id },
      });
      if (res.code !== 200) return this.$message.error(res.msg);
      this.allChannel = res.data;
    },
    async getAllDeveloper() {
      const res = await this.$api["data/hospitalStaff/getAllByJobName"]({ hospitalJobName: "网电人员" });
      if (res.code !== 200) return this.$message.error(res.msg);
      this.allDeveloper = res.data;
    },
    channelChange(id) {
      this.getAllChannel(id);
      this.regions.forEach(item => {
        if (item.id === id) {
          this.$set(this.addCustomersData, "developmentChannels", item.name);
        }
      });
      this.$set(this.addCustomersData, "channelNameId", "");
    },
    developersChange(id) {
      this.allDeveloper.forEach(item => {
        if (item.id === id) {
          this.addCustomersData.developersName = item.usrName;
        }
      });
    },
    channelNameChange(id) {
      this.allChannel.forEach(item => {
        if (item.id === id) {
          this.$set(this.addCustomersData, "channelName", item.name);
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.editor__content{
  border: 1px solid #d3dff7;
}
.info-title{
  margin:40px 0 20px 0;
  font-weight: 800;
}
.info-titles{
  margin:0px 0 20px 0;
  font-weight: 800;
}
.el-form-item{
  display: flex;
}
/deep/ .el-form-item .el-form-item__label{
  text-align: right !important;
}
/deep/ .el-select-y{
  width: 237.5px;
}
/deep/.ProseMirror p{
  margin: 0px !important;
}
.el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
  margin-bottom: 18px;
}
</style>
